﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace TunesHelper
{
  public partial class HotKeyDialog : Form
  {
    static readonly List<Keys> s_forbiddenKeys = new List<Keys> 
        { 
            Keys.RShiftKey, Keys.LShiftKey, Keys.ShiftKey, Keys.Shift,
            Keys.Alt,
            Keys.RMenu, Keys.LMenu, Keys.Menu,
            Keys.RControlKey, Keys.LControlKey, Keys.ControlKey, Keys.Control,
            Keys.RWin, Keys.LWin, 
            Keys.CapsLock, Keys.Pa1
        };

    public ModKeys Modifiers
    {
      get
      {
        var win = _winChkBox.Checked ? ModKeys.Win : ModKeys.None;
        var ctrl = _ctrlChkBox.Checked ? ModKeys.Control : ModKeys.None;
        var alt = _altChkBox.Checked ? ModKeys.Alt : ModKeys.None;
        var shift = _shiftChkBox.Checked ? ModKeys.Shift : ModKeys.None;
        return win | ctrl | alt | shift;
      }
    }

    public Keys Key
    {
      get { return (Keys)_keyCombo.SelectedItem; }
    }

    public Hotkey GetHotkey()
    {
      return new Hotkey(Modifiers, Key);
    }

    public HotKeyDialog(Hotkey hk)
    {
      InitializeComponent();
      PopulateKeys();
      InitHotkey(hk);
    }

    private void PopulateKeys()
    {
      foreach (Keys key in Enum.GetValues(typeof(Keys)))
      {
        if (s_forbiddenKeys.Contains(key) || (int)key < 33 || (int)key > 251) continue;
        if (_keyCombo.Items.Contains(key)) continue;
        _keyCombo.Items.Add(key);
      }
    }

    private void InitHotkey(Hotkey hk)
    {
      _winChkBox.Checked = (hk.Modifier & ModKeys.Win) == ModKeys.Win;
      _ctrlChkBox.Checked = (hk.Modifier & ModKeys.Control) == ModKeys.Control;
      _altChkBox.Checked = (hk.Modifier & ModKeys.Alt) == ModKeys.Alt;
      _shiftChkBox.Checked = (hk.Modifier & ModKeys.Shift) == ModKeys.Shift;
      for (var i = 0; i < _keyCombo.Items.Count; i++)
      {
        var key = (Keys)_keyCombo.Items[i];
        if (key != hk.Key) continue;
        _keyCombo.SelectedIndex = i;
        break;
      }
    }

    private void Combo_KeyPress(object sender, KeyPressEventArgs e)
    {
      e.Handled = true;
    }

    private void Combo_KeyDown(object sender, KeyEventArgs e)
    {
      for (var i = 0; i < _keyCombo.Items.Count; i++)
      {
        var key = (Keys)_keyCombo.Items[i];
        if (key != e.KeyCode) continue;
        _keyCombo.SelectedIndex = i;
        break;
      }
    }
  }
}
